package com.yc.fav.servlet;

import com.google.gson.Gson;
import com.yc.fav.entity.User;
import com.yc.fav.service.BizException;
import com.yc.fav.service.IUserService;
import com.yc.fav.service.impl.UserServiceImpl;
import com.yc.fav.vo.Result;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Company 源辰信息
 *
 * @author navy
 * @date 2024/10/28
 * Email haijunzhou@hnit.edu.cn
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {

    IUserService userService = new UserServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json;charset=utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        Result ret;
        try {
            User login = userService.login(username, password);
            req.getSession().setAttribute("myinfo",login);
            ret = new Result(1, "登录成功!", login);
        } catch (BizException e) {
            ret = new Result(e.getCode(), e.getMessage(), null);
        }
        String json = new Gson().toJson(ret);
        resp.getWriter().append(json);
    }
}

